import sys
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QWidget, QTabWidget,
                             QGroupBox, QLabel, QLineEdit, QTextEdit, QComboBox,
                             QPushButton, QCheckBox, QListWidget, QListWidgetItem,
                             QMessageBox, QFormLayout, QSplitter, QScrollArea)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont, QColor, QPalette

from config_manager import get_config_manager, TranslationPreset


class PresetEditor(QWidget):
    """预设编辑器"""
    preset_saved = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.current_preset = None
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # 预设基本信息
        basic_group = QGroupBox("预设基本信息")
        basic_layout = QFormLayout(basic_group)
        
        self.name_edit = QLineEdit()
        self.name_edit.setPlaceholderText("输入预设名称（英文、数字、下划线）")
        basic_layout.addRow("预设名称:", self.name_edit)
        
        self.description_edit = QLineEdit()
        self.description_edit.setPlaceholderText("描述预设用途")
        basic_layout.addRow("描述:", self.description_edit)
        
        self.enabled_checkbox = QCheckBox("启用此预设")
        self.enabled_checkbox.setChecked(True)
        basic_layout.addRow("", self.enabled_checkbox)
        
        layout.addWidget(basic_group)
        
        # 语言设置
        lang_group = QGroupBox("语言设置")
        lang_layout = QFormLayout(lang_group)
        
        self.source_lang_combo = QComboBox()
        self.source_lang_combo.addItems(["English", "Chinese", "French", "Spanish", "German", "Japanese"])
        lang_layout.addRow("源语言:", self.source_lang_combo)
        
        self.target_lang_combo = QComboBox()
        self.target_lang_combo.addItems(["Chinese", "English", "French", "Spanish", "German", "Japanese"])
        lang_layout.addRow("目标语言:", self.target_lang_combo)
        
        layout.addWidget(lang_group)
        
        # 自定义提示词
        prompt_group = QGroupBox("自定义提示词")
        prompt_layout = QVBoxLayout(prompt_group)
        
        self.prompt_edit = QTextEdit()
        self.prompt_edit.setPlaceholderText(
            "输入自定义提示词，这将添加到翻译请求中。\n"
            "例如：请用专业的语气翻译以下内容，保持学术严谨性。\n"
            "或：请用轻松幽默的语气翻译，适合社交媒体使用。"
        )
        self.prompt_edit.setMaximumHeight(150)
        prompt_layout.addWidget(self.prompt_edit)
        
        # 示例提示词按钮
        example_layout = QHBoxLayout()
        example_layout.addWidget(QLabel("快速插入示例:"))
        
        casual_btn = QPushButton("轻松语气")
        casual_btn.clicked.connect(lambda: self.insert_example("请用轻松自然的语气翻译以下内容"))
        example_layout.addWidget(casual_btn)
        
        formal_btn = QPushButton("正式语气")
        formal_btn.clicked.connect(lambda: self.insert_example("请用正式专业的语气翻译以下内容"))
        example_layout.addWidget(formal_btn)
        
        academic_btn = QPushButton("学术语气")
        academic_btn.clicked.connect(lambda: self.insert_example("请用学术严谨的语气翻译以下专业内容"))
        example_layout.addWidget(academic_btn)
        
        example_layout.addStretch()
        prompt_layout.addLayout(example_layout)
        
        layout.addWidget(prompt_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        self.save_btn = QPushButton("保存预设")
        self.save_btn.clicked.connect(self.save_preset)
        button_layout.addWidget(self.save_btn)
        
        self.reset_btn = QPushButton("重置")
        self.reset_btn.clicked.connect(self.reset_form)
        button_layout.addWidget(self.reset_btn)
        
        self.delete_btn = QPushButton("删除预设")
        self.delete_btn.clicked.connect(self.delete_preset)
        self.delete_btn.setEnabled(False)
        button_layout.addWidget(self.delete_btn)
        
        button_layout.addStretch()
        layout.addLayout(button_layout)
        
        layout.addStretch()
    
    def insert_example(self, text: str):
        """插入示例提示词"""
        current_text = self.prompt_edit.toPlainText()
        if current_text:
            current_text += "\n"
        self.prompt_edit.setPlainText(current_text + text)
    
    def load_preset(self, preset: TranslationPreset):
        """加载预设到编辑器"""
        self.current_preset = preset
        
        self.name_edit.setText(preset.name)
        self.name_edit.setEnabled(False)  # 编辑时禁用名称修改
        self.description_edit.setText(preset.description)
        self.enabled_checkbox.setChecked(preset.enabled)
        self.source_lang_combo.setCurrentText(preset.source_language)
        self.target_lang_combo.setCurrentText(preset.target_language)
        self.prompt_edit.setPlainText(preset.custom_prompt)
        
        self.delete_btn.setEnabled(True)
    
    def new_preset(self):
        """创建新预设"""
        self.current_preset = None
        self.reset_form()
        self.name_edit.setEnabled(True)
        self.delete_btn.setEnabled(False)
    
    def reset_form(self):
        """重置表单"""
        if self.current_preset:
            self.load_preset(self.current_preset)
        else:
            self.name_edit.clear()
            self.name_edit.setEnabled(True)
            self.description_edit.clear()
            self.enabled_checkbox.setChecked(True)
            self.source_lang_combo.setCurrentText("English")
            self.target_lang_combo.setCurrentText("Chinese")
            self.prompt_edit.clear()
            self.delete_btn.setEnabled(False)
    
    def save_preset(self):
        """保存预设"""
        name = self.name_edit.text().strip()
        if not name:
            QMessageBox.warning(self, "错误", "请输入预设名称")
            return
        
        # 验证名称格式
        if not all(c.isalnum() or c == '_' for c in name):
            QMessageBox.warning(self, "错误", "预设名称只能包含字母、数字和下划线")
            return
        
        description = self.description_edit.text().strip()
        source_lang = self.source_lang_combo.currentText()
        target_lang = self.target_lang_combo.currentText()
        custom_prompt = self.prompt_edit.toPlainText().strip()
        enabled = self.enabled_checkbox.isChecked()
        
        preset = TranslationPreset(
            name=name,
            description=description,
            source_language=source_lang,
            target_language=target_lang,
            custom_prompt=custom_prompt,
            enabled=enabled
        )
        
        # 保存预设
        config_manager = get_config_manager()
        config_manager.add_preset(preset)
        
        QMessageBox.information(self, "成功", f"预设 '{name}' 已保存")
        self.preset_saved.emit()
    
    def delete_preset(self):
        """删除当前预设"""
        if not self.current_preset:
            return
        
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除预设 '{self.current_preset.name}' 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            config_manager = get_config_manager()
            config_manager.delete_preset(self.current_preset.name)
            QMessageBox.information(self, "成功", "预设已删除")
            self.new_preset()
            self.preset_saved.emit()


class SettingsDialog(QDialog):
    """设置对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.config_manager = get_config_manager()
        self.init_ui()
        self.load_presets()
    
    def init_ui(self):
        self.setWindowTitle("翻译预设设置")
        self.setGeometry(200, 200, 900, 600)
        
        layout = QVBoxLayout(self)
        
        # 创建标签页
        tab_widget = QTabWidget()
        layout.addWidget(tab_widget)
        
        # 预设管理标签页
        preset_tab = QWidget()
        preset_layout = QVBoxLayout(preset_tab)
        
        # 预设管理分割器
        preset_splitter = QSplitter(Qt.Orientation.Horizontal)
        preset_layout.addWidget(preset_splitter)
        
        # 左侧：预设列表
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        preset_list_group = QGroupBox("预设列表")
        preset_list_layout = QVBoxLayout(preset_list_group)
        
        self.preset_list = QListWidget()
        self.preset_list.currentItemChanged.connect(self.on_preset_selected)
        preset_list_layout.addWidget(self.preset_list)
        
        # 预设列表按钮
        list_buttons_layout = QHBoxLayout()
        
        self.new_preset_btn = QPushButton("新建预设")
        self.new_preset_btn.clicked.connect(self.new_preset)
        list_buttons_layout.addWidget(self.new_preset_btn)
        
        list_buttons_layout.addStretch()
        preset_list_layout.addLayout(list_buttons_layout)
        
        left_layout.addWidget(preset_list_group)
        preset_splitter.addWidget(left_widget)
        
        # 右侧：预设编辑器
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        self.preset_editor = PresetEditor()
        self.preset_editor.preset_saved.connect(self.load_presets)
        right_layout.addWidget(self.preset_editor)
        
        preset_splitter.addWidget(right_widget)
        preset_splitter.setSizes([300, 600])
        
        tab_widget.addTab(preset_tab, "预设管理")
        
        # 主题设置标签页
        theme_tab = QWidget()
        theme_layout = QVBoxLayout(theme_tab)
        
        # 主题设置
        theme_group = QGroupBox("主题设置")
        theme_group_layout = QVBoxLayout(theme_group)
        
        # 主题选择
        theme_selection_layout = QHBoxLayout()
        theme_selection_layout.addWidget(QLabel("选择主题:"))
        
        self.theme_combo = QComboBox()
        themes = self.config_manager.get_available_themes()
        for theme_id, theme_data in themes.items():
            self.theme_combo.addItem(theme_data["name"], theme_id)
        
        current_theme = self.config_manager.get_current_theme_name()
        index = self.theme_combo.findData(current_theme)
        if index >= 0:
            self.theme_combo.setCurrentIndex(index)
        
        self.theme_combo.currentIndexChanged.connect(self.on_theme_changed)
        theme_selection_layout.addWidget(self.theme_combo)
        
        theme_selection_layout.addStretch()
        theme_group_layout.addLayout(theme_selection_layout)
        
        # 主题预览
        preview_group = QGroupBox("主题预览")
        preview_layout = QVBoxLayout(preview_group)
        
        self.preview_widget = QWidget()
        self.preview_widget.setMinimumHeight(200)
        preview_layout.addWidget(self.preview_widget)
        
        theme_group_layout.addWidget(preview_group)
        
        # 应用主题按钮
        apply_theme_btn = QPushButton("应用主题")
        apply_theme_btn.clicked.connect(self.apply_theme)
        theme_group_layout.addWidget(apply_theme_btn)
        
        theme_layout.addWidget(theme_group)
        theme_layout.addStretch()
        
        tab_widget.addTab(theme_tab, "主题设置")
        
        # 初始化主题预览
        self.update_theme_preview()
        
        # 底部按钮
        button_layout = QHBoxLayout()
        
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        button_layout.addWidget(close_btn)
        
        button_layout.addStretch()
        layout.addLayout(button_layout)
    
    def load_presets(self):
        """加载预设列表"""
        self.preset_list.clear()
        
        presets = self.config_manager.presets
        for preset in presets:
            item = QListWidgetItem(preset.name)
            if not preset.enabled:
                item.setForeground(Qt.GlobalColor.gray)
                item.setText(f"{preset.name} (禁用)")
            
            item.setData(Qt.ItemDataRole.UserRole, preset)
            self.preset_list.addItem(item)
    
    def on_preset_selected(self, current, previous):
        """预设选择改变"""
        if current is None:
            self.preset_editor.new_preset()
            return
        
        preset = current.data(Qt.ItemDataRole.UserRole)
        if preset:
            self.preset_editor.load_preset(preset)
    
    def new_preset(self):
        """创建新预设"""
        self.preset_list.clearSelection()
        self.preset_editor.new_preset()
    
    def on_theme_changed(self):
        """主题选择改变"""
        self.update_theme_preview()
    
    def update_theme_preview(self):
        """更新主题预览"""
        theme_id = self.theme_combo.currentData()
        theme = self.config_manager.get_available_themes().get(theme_id, {})
        
        if theme:
            # 设置预览窗口的背景色
            self.preview_widget.setStyleSheet(f"""
                QWidget {{
                    background-color: {theme.get('background', '#ffffff')};
                    color: {theme.get('foreground', '#000000')};
                    border: 2px solid {theme.get('primary', '#007acc')};
                    border-radius: 5px;
                }}
            """)
    
    def apply_theme(self):
        """应用选择的主题"""
        theme_id = self.theme_combo.currentData()
        if theme_id:
            self.config_manager.set_theme(theme_id)
            QMessageBox.information(self, "成功", f"主题已切换到: {self.theme_combo.currentText()}")
            # 发射信号通知主窗口需要重新应用主题
            self.theme_applied = True


if __name__ == "__main__":
    from PyQt6.QtWidgets import QApplication
    
    app = QApplication(sys.argv)
    dialog = SettingsDialog()
    dialog.exec()
    sys.exit()